package com.gaoch.simweather.ui.place

import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import com.gaoch.simweather.R

import com.gaoch.simweather.logic.model.PlaceResponse
import com.gaoch.simweather.tools.LogUtil
import com.gaoch.simweather.ui.weather.WeatherActivity


class PlaceAdapter(private val fragment:PlaceFragment,private val placeList: List<PlaceResponse.Location>): RecyclerView.Adapter<PlaceAdapter.ViewHolder>() {

    inner class ViewHolder(view:View):RecyclerView.ViewHolder(view){
        val placeName:TextView=view.findViewById(R.id.item_place_tv_name)
        val placeDetail:TextView=view.findViewById(R.id.item_place_tv_detail)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view=LayoutInflater.from(parent.context).inflate(R.layout.item_place,parent,false)
        val holder=ViewHolder(view)
        holder.itemView.setOnClickListener {
            val position=holder.adapterPosition
            val location=placeList[position].id
            val cityName=placeList[position].name
            LogUtil.d(msg = "location=${location},cityName=${cityName}")
            val intent=Intent(parent.context,WeatherActivity::class.java).apply {
                putExtra("location",location)
                putExtra("cityName",cityName)
            }
            fragment.viewModel.savePlace(placeList[position])
            fragment.startActivity(intent)
        }
        return holder
    }

    override fun getItemCount()=placeList.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val place=placeList[position]
        holder.placeName.text=place.name
        holder.placeDetail.text="${place.country} ${place.adm1} ${place.adm2}"
    }
}